<!DOCTYPE html>
<html lang="zn">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="../js/vue.js"></script>
  <title>列表排序</title>
  <style>
    button {
      margin-bottom: 20px;
    }
  </style>
</head>

<body>
  <div id="root">
    <!-- 遍历数组 -->
    <h2>人员列表(遍历数组)</h2>
    <input type="text" v-model="keyWord" placeholder="请输入关键字">
    <button @click="sortType=1">年龄升序</button>
    <button @click="sortType=2">年龄降序</button>
    <button @click="sortType=0">原顺序</button>
    <ul>
      <li v-for="(person,index) in filPersonList" :key="index">
        {{person.name}}-{{person.age}}
      </li>
    </ul>
  </div>

  <script>
    Vue.config.productionTip = false
    // 计算属性实现
    new Vue({
      el: '#root',
      data() {
        return {
          keyWord: '',
          sortType:0,//0:原排序 1:升序 2:降序
          personList: [
            { id: '001', name: '张三', age: 26 },
            { id: '002', name: '李四', age: 25 },
            { id: '003', name: '王五', age: 17 },
            { id: '004', name: '老王', age: 16 },
            { id: '005', name: '王三', age: 50 },
          ]
        }
      },
      computed:{
        filPersonList(){
          const arr =  this.personList.filter((person)=>{
            return person.name.indexOf(this.keyWord) !==-1
          })
          // 判断一下是否需要排序
          if(this.sortType){
            arr.sort((p1,p2)=>{
              // 三元表达式 
              return this.sortType ===1 ? p1.age-p2.age : p2.age-p1.age
            })
          }
          return arr
        }
      }
      
    })
  </script>
</body>

</html>